import { Component, ElementRef, ViewChild, Renderer2, ViewEncapsulation } from '@angular/core';
import { ApesField } from './apes-field';
import { ApiService } from '@core/services/http/api.service';
import { Events } from '@core/services/events/Events';
import { ExpressionService } from '@core/services/expression/ExpressionService';
import { SubjectService } from '@core/services/events/subject.service';
import set = Reflect.set;
import { Subject } from 'rxjs/internal/Subject';
import { ENTER } from '@angular/cdk/keycodes';

@Component({
  selector: 'formly-field-input',
  encapsulation: ViewEncapsulation.None,
  template: `
    <!--    <input apes-input [formControl]="formControl" [formlyAttributes]="field"-->
    <!--           [placeholder]="to.placeholder"-->
    <!--           [readonly]="readonly"-->
    <!--           [disabled]="to.disabled"/>-->
    <input apes-input [formControl]="formControl" [formlyAttributes]="field"
           #inputElement
           [placeholder]="formatter(to.placeholder)"
           [readonly]="readonly"
           (keydown)="onKeyDown($event)"
           (ngModelChange)="onChange($event)"
           [disabled]="to.disabled"/>
  `,
})
export class FormlyFieldInput extends ApesField {

  @ViewChild('inputElement', { static: false }) inputElement: ElementRef;

  constructor(protected apiService: ApiService, protected events: Events, protected expressionService: ExpressionService, protected subject: SubjectService,
              protected elementRef: ElementRef, protected renderer: Renderer2) {
    super(apiService, events, expressionService, subject);
  }

  value: any = '';
  loading: any = null;

  ngOnInit() {
    this.addDefalutPlaceholder('请输入');
    this.addEventListener(this.elementRef, this.renderer);
  }

  ngAfterViewInit() {
    const config = this.to;
    const ctx = config.componentRef.formState;
    if (config.hasOwnProperty('editFocus')) {
      this.subject.subscribe(ctx, this.subject.event_form_button, data => {
        setTimeout(() => {
          this.inputElement.nativeElement.focus();
        }, 500);
      });
    }
  }

  get readonly() {
    return this.to.readonly;
  }

  onChange(value: string): void {
    if (this.to.hasOwnProperty('regFormatter')) {
      if (this.loading) {
        clearTimeout(this.loading);
        this.loading = null;
      }
      this.loading = setTimeout(() => {
        this.value = '';
        this.updateValue(value);
      }, 100);
    }
  }

  updateValue(value: string): void {
    let regStr: string = this.to.regFormatter;
    // tslint:disable-next-line:no-eval
    const regExp = eval(regStr);
    if (value != null && value != '' && value != undefined) {
      for (let i = 0; i < value.length; i++) {
        this.value = this.value + value.substr(i, 1).replace(regExp, '');
      }
    }

    if (this.inputElement) {
      this.inputElement.nativeElement.value = this.value;
      this.formControl.patchValue(this.value);
    }
  }

  formatter(expression: string) {
    let placeholder;
    if (expression.indexOf('return') >= 0) {
      placeholder = this.expressionService.eval(expression, {
        context: this.formState,
        model: this.formState.model,
      });
    } else {
      placeholder = expression;
    }
    return placeholder;
  }

  onKeyDown(event): void {
    if (event.keyCode === ENTER) {
      event.preventDefault();
      event.stopPropagation();
    }
  }
}
